@file:OptIn(
    ExperimentalFoundationApi::class, ExperimentalFoundationApi::class,
    ExperimentalMaterial3Api::class
)

package com.lly.tboc.zhouyi

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.rememberDrawerState
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.currentBackStackEntryAsState
import com.lly.tboc.R
import com.lly.tboc.zhouyi.everyday.EverydayOneGuaUI
import com.lly.tboc.zhouyi.vm.GuaViewModel
import com.lly.tboc.zhouyi.vo.Gua
import com.lly.ui.GuaView
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GuaListScreen(
    guaId: Int,
    navController: NavController,
    onClick: (Gua) -> Unit,
    onLongClick: (Gua) -> Unit,
    viewModel: GuaViewModel = hiltViewModel(),
    navigationAction: () -> Unit,
) {
    Surface(color = MaterialTheme.colorScheme.primary) {
        val guaFlow = viewModel.get()
        val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
        val scope = rememberCoroutineScope()
        val scrollState = rememberLazyListState()
        val scrollToGua: (guaId: Int) -> Unit = {
            scope.launch {
                drawerState.close()
                scrollState.scrollToItem(
                    viewModel.getPositionByGuaId(it)
                )
            }
        }
        LaunchedEffect(key1 = guaId) {
            if (guaId > 0) {
                guaFlow.first { it.isNotEmpty() }
                scrollToGua(guaId)
            }
        }
        ModalNavigationDrawer(
            drawerState = drawerState,
            drawerContent = {
                ModalDrawerSheet {
                    EverydayOneGuaUI(
                        guaFlow.collectAsStateWithLifecycle(initialValue = emptyList()),
                        scrollToGua,
                    ) { guaId, yaoId ->
                        viewModel.getYao(guaId, yaoId)
                    }
                    val navBackStackEntry by navController.currentBackStackEntryAsState()
                    listOf(
                        Screen.ZhouYi,
                        Screen.Dao,
                        Screen.Explore,
                        Screen.CoroutineExplore,
                        Screen.Books,
                        Screen.Setting,
                    ).forEach { screen ->
                        HorizontalDivider(Modifier.padding(4.dp))
                        NavigationDrawerItem(label = { Text(text = stringResource(id = screen.resourceId)) },
                            icon = {
                                Image(
                                    painter = painterResource(id = screen.iconId),
                                    contentDescription = stringResource(id = screen.resourceId)
                                )
                            },
                            selected = navBackStackEntry?.destination?.hierarchy?.any { screen.route == it.route } == true,
                            onClick = {
                                if (screen.enable) {
                                    navController.navigate(screen.route) {
                                        // Pop up to the start destination of the graph to
                                        // avoid building up a large stack of destinations
                                        // on the back stack as users select items
                                        popUpTo(navController.graph.findStartDestination().id) {
                                            saveState = true
                                        }
                                        // Avoid multiple copies of the same destination when
                                        // reselecting the same item
                                        launchSingleTop = true
                                        // Restore state when reselecting a previously selected item
                                        restoreState = true
                                    }
                                    scope.launch {
                                        drawerState.close()
                                    }
                                } else {
                                }
                            })
                    }
                }
            },

            ) {
            val scrollBehavior =
                TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())

            Scaffold(modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
                containerColor = Color.Transparent,
                floatingActionButton = {
                    val context = LocalView.current.context
                    if (viewModel.showShareButtonState.value.isNotEmpty()) {
                        ExtendedFloatingActionButton(
                            text = {
                                Text(text = "已保存到:\n" + viewModel.showShareButtonState.value)
                            },
                            icon = {
                                Icon(
                                    imageVector = Icons.Filled.Share,
                                    contentDescription = "share"
                                )
                            },
                            onClick = {
                                viewModel.doShare(context)
                            },
                        )
                    }
                },
                topBar = {
                    TopBar(
                        scrollBehavior,
                        navigationAction,
                        {
                            navController.navigate(Screen.GuaSearch.searchRoute(""))
                        },
                    ) { viewModel.saveZhouYiToFile() }
                }) { innerPadding ->
                contentView(
                    guas = guaFlow.map { it.map { gua -> (GuaWrap(gua)) } }
                        .collectAsStateWithLifecycle(emptyList()),
                    onClick, onLongClick, scrollState, Modifier.padding(innerPadding)
                )

            }

        }
    }

}

class GuaWrap(val gua: Gua, val isFold: MutableState<Boolean> = mutableStateOf(true))

@Composable
fun contentView(
    guas: State<List<GuaWrap>?>,
    goDetailPage: (Gua) -> Unit,
    goEditPage: (Gua) -> Unit,
    scrollState: LazyListState = rememberLazyListState(),
    modifier: Modifier,
) {
    LazyColumn(
        modifier = modifier,
        state = scrollState
    ) {
        guas.value?.let { guas ->
            items(guas, key = { it.gua.id }) {
                guaContent(it.gua, it.isFold, goDetailPage, goEditPage)
            }
        }
    }
}

@Composable
fun guaContent(
    it: Gua,
    isFold: MutableState<Boolean>,
    goDetailPage: (Gua) -> Unit,
    goEditPage: (Gua) -> Unit
) {
    Card(
        /* onClick = {
         },*/

        elevation = CardDefaults.cardElevation(
            defaultElevation = 0.dp
        ),
        border = BorderStroke(1.dp, Color.Black),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.7f),
        ),
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .combinedClickable(
                enabled = true,
                onLongClick = {
                    goEditPage(it)
                },
                onDoubleClick = {
                    isFold.value = !isFold.value
                },
                onClick = {
                    goDetailPage(it)
                }
            )
    ) {
        Column(modifier = Modifier.padding(8.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(text = it.name, style = MaterialTheme.typography.titleLarge)
                Spacer(modifier = Modifier.size(8.dp))
                val yaoColor = LocalContentColor.current
                GuaView(
                    yaoes = it.yaoViewData,
                    selectedColor = yaoColor,
                    color = yaoColor,
                    modifier = Modifier
                        .height(20.dp)
                        .width(20.dp)
                )

            }
            Text(text = it.ci, style = MaterialTheme.typography.labelLarge)
            Spacer(modifier = Modifier.size(8.dp))
            AnimatedVisibility(!isFold.value) {
                it.tuan?.let {
                    if (it.isNotEmpty()) {
                        Text(text = it)
                        Spacer(modifier = Modifier.size(8.dp))
                    }
                }
            }
            it.xiang?.let {
                if (it.isNotEmpty()) {
                    Text(text = it, style = MaterialTheme.typography.bodyMedium)
                    Spacer(modifier = Modifier.size(8.dp))
                }
            }
            AnimatedVisibility(!isFold.value) {
                it.wu?.let {
                    if (it.isNotEmpty()) {
                        Text(text = it, style = MaterialTheme.typography.bodySmall)
                        Spacer(modifier = Modifier.size(8.dp))
                    }
                }
            }
        }
    }
}

@Composable
@OptIn(ExperimentalMaterial3Api::class)
private fun TopBar(
    scrollBehavior: TopAppBarScrollBehavior,
    navigationAction: () -> Unit,
    goGuaSearchPage: () -> Unit,
    saveZhouYiToFile: () -> Unit
) {
    CenterAlignedTopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary,
        ),
        title = {
            Text(
                text = stringResource(id = R.string.app_name),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        },
        navigationIcon = {
            IconButton(onClick = navigationAction) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "Localized description"
                )
            }
        },
        actions = {
            IconButton(onClick = {
                goGuaSearchPage()
            }) {
                Icon(imageVector = Icons.Filled.Search, contentDescription = "search")
            }
            IconButton(onClick = { saveZhouYiToFile() }) {
                Icon(
                    imageVector = Icons.Filled.Menu,
                    contentDescription = "Localized description"
                )
            }
        },
        scrollBehavior = scrollBehavior,
    )
}
